# -*- coding: utf-8 -*-

# Copyright (C) 2017 Intel Corporation.  All rights reserved.
# Copyright (c) WanSheng Intelligent Corp. All rights reserved.

#
# Licensed under the Apache License, Version 2.0 (the "License");
#


import sys
from ..model.parser_base import ParserBase
from ..model.property_data import PropertyData
from ..internals.resource_data_lwmm import ResourceDataLWM2M
import json
import traceback

'''
{“e”:[
{"n":"1/2","v":"22.4","t":"-5"},
{"n":"1/2","v":"22.9","t":"-30"},
{"n":"1/2","v":"24.1","t":"-50"}],
"bt":"25462634"
}

{
   "bn": "/1/0/1/", 
   "e": [
      {
         "v": 300, 
         "n": "1"
      }
   ]
}


'''

class LWM2MDataParser(ParserBase):
    def parse(self, text, fmt):
        if type(text) is not str:
            print("OCFDataParser, text is not string. " + str(type(text)))
            return None
        
        try:
            json_object = json.loads(text)
            if json_object is None:
                return None
            property_items = []
            bt = json_object.get("bt")
            bn = ""
            if "bn" in json_object:
                bn = json_object["bn"]
                
            
            json_array = json_object.get("e")
            if json_array is None:
                return None
            
            for i in json_array:
                element_json = i
                prop_name = element_json["n"]
                value = ""
                if "v" in element_json:
                    value = element_json["v"]
                elif "bv" in element_json:
                    value = element_json["bv"]
                elif "sv" in element_json:
                    value = element_json["sv"]
                    
                property_data = PropertyData(prop_name, value)
                t = element_json.get("t")
                
                # the time info is optional in the lwm2m payload
                point_time = 0
                if bt is not None:
                    point_time += bt
                if t is not None:
                    point_time += t
                    
                if point_time != 0:
                    property_data.set_time(point_time)

                property_items.append(property_data)
                
                    
            data = ResourceDataLWM2M(text, fmt)
            data.base_name = bn
            data.items = property_items
            data.is_parsed = True
            return data
        
        except Exception as e:
            print(traceback.format_exc())
            return None
